import appConfig from '../config/config.js'

const buildStrParams = (params) => {
	let strParams = ''
	let i = 0
	for (let k in params) {
		let q = ''
		if (i === 0) {
			q = '?'
		} else {
			q = '&'
		}
		strParams = strParams + q + k + '=' + params[k]
		i++
	}
	return strParams
}


const post = (url, params, data, config = null) => {
	Object.assign
	const defaultConfig = {
		method: 'POST',
		showLoading: true,
		base_url: '',
		requireLogin: false,
		forceLogin: false
	}
	const finalConfig = config ? Object.assign(defaultConfig, config) : defaultConfig
	finalConfig.showLoading && uni.showLoading({
		title: '加载中'
	})
	return new Promise((resolve) => {
		uni.request({
			method: finalConfig.method,
			url: (finalConfig.base_url ? finalConfig.base_url : appConfig.apiUrl) + url + buildStrParams(params),
			data: data,
			timeout: 10000,
			header: (() => {
				let config = {
					'content-type': 'application/x-www-form-urlencoded'
				}
				return config
			})(),
			success: (res) => {
				if(res.statusCode!=200){
					uni.showToast({
						title: "错误！"+res.statusCode,
						icon: 'none',
						duration: 2000
					});
				}
				const {
					code,
					data
				} = res.data
				resolve(res.data)
			},
			fail:(res)=> {
				uni.hideLoading()
				uni.showToast({
					title: res.errMsg,
					icon: 'none',
					duration: 5000
				});
			},
			complete: () => {
				finalConfig.showLoading && uni.hideLoading()
			}
		})
	})
}

export const request = {
  send: (url, params, data, config) => {
  		return post(url, params, data, config)
  }
}
